package com.android.powerbankpad.network.retrofit;

import android.util.Log;

import com.android.powerbankpad.config.Constants;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.LogcatUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HeaderInterceptor implements Interceptor {
    private Map<String, String> mHeaderParamsMap = new HashMap<>();

    public HeaderInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        Log.d("HeaderInterceptor", "add common params" + oldRequest.url());
        LogcatUtils.e("  请求url  : " + oldRequest.url().toString());
        // 新的请求
        Request.Builder requestBuilder = oldRequest.newBuilder();
        requestBuilder.method(oldRequest.method(), oldRequest.body());
        int currentTimeMillis = (int) (System.currentTimeMillis() / 1000);
        requestBuilder.addHeader("time", currentTimeMillis + "");
        requestBuilder.addHeader("lang", CacheUtils.getString(Constants.langCode));
        requestBuilder.addHeader("ocode", CacheUtils.getString(Constants.ocode));
        //添加公共参数,添加到header中
        if (mHeaderParamsMap.size() > 0) {
            for (Map.Entry<String, String> params : mHeaderParamsMap.entrySet()) {
                requestBuilder.header(params.getKey(), params.getValue());
            }
        }
        Request newRequest = requestBuilder.build();
        return chain.proceed(newRequest);
    }

    public static class Builder {
        HeaderInterceptor mHttpCommonInterceptor;

        public Builder() {
            mHttpCommonInterceptor = new HeaderInterceptor();
        }

        public Builder addHeaderParams(String key, String value) {
            mHttpCommonInterceptor.mHeaderParamsMap.put(key, value);
            return this;
        }

        public Builder addHeaderParams(String key, int value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, float value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, long value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, double value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public HeaderInterceptor build() {
            return mHttpCommonInterceptor;
        }

    }


}
